﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RFBR.Core
{
    class Analyze
    {
        string text;
        List<string> lemms;
        string[] stopwords;


        public List<string> Start(string txt)
        {
            text = txt;
            lemms = Lemmatization();
            return lemms;
        }


        List<string> Lemmatization()
        {
            List<string> lemms = new List<string>();
            //Массив всех лемм
            string[] words = MyStem(text);
            lemms = ClearLemms(words);
            return lemms;
        }

        string[] MyStem(string input)
        {
            System.Diagnostics.Process myStem = new Process();
            myStem.StartInfo.FileName = "mystem.exe";
            myStem.StartInfo.CreateNoWindow = true;
            using (StreamWriter writer = new StreamWriter(@"buf.txt", false, Encoding.Default))
                writer.WriteLine(input);
            myStem.StartInfo.Arguments = "-nl buf.txt out.txt";
            myStem.Start();
            myStem.WaitForExit();
            myStem.Close();
            StreamReader reader = new StreamReader(@"out.txt", Encoding.Default);
            string[] words = reader.ReadToEnd().Split('\n');
            reader.Close();
            return words;
        }

        List<string> ClearLemms(string[] words)
        {
            List<string> lemms = new List<string>();
            GetStopwords();
            string lemm = "";
            //Очищение списка лемм от стоп-слов и повторяющихся лемм
            for (int i = 0; i < words.Length; i++)
            {
                lemm = words[i];
                if (lemm.IndexOf("|") != -1) lemm = lemm.Substring(0, lemm.IndexOf("|"));
                while (lemm.IndexOf("?") != -1) lemm = lemm.Remove(lemm.IndexOf("?"), 1);
                if (lemms.IndexOf(lemm) == -1 && !IsStopword(lemm))
                    lemms.Add(lemm);
            }
            return lemms;
        }


        void GetStopwords()
        {
            //Получение списка стоп-слов
            StreamReader reader = new StreamReader(@"stop_words.txt", System.Text.Encoding.Default);
            stopwords = reader.ReadToEnd().Split('\n');
            reader.Close();
            for (int j = 0; j < stopwords.Length; j++)
                if (stopwords[j].IndexOf("\r") != -1)
                    stopwords[j] = stopwords[j].Remove(stopwords[j].IndexOf("\r"), 1);
        }

        bool IsStopword(string lemm)
        {
            for (int j = 0; j < stopwords.Length; j++)
                if (lemm == stopwords[j])
                    return true;
            return false;
        }
    }
}
